package com.liutaw.nanjingair.presenter;

import android.content.Context;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.content.ContextCompat;
import android.util.Log;

import com.google.gson.Gson;
import com.liutaw.nanjingair.models.test;
import com.liutaw.nanjingair.views.activities.AndroidApplication;
import com.liutaw.nanjingair.views.fragments.IIndexFragment;
import com.szjlxh.domain.interactor.BaseWeatherInfoUserCase;
import com.szjlxh.domain.model.SunInfo;
import com.szjlxh.domain.model.index.Station;
import com.szjlxh.domain.model.index.WeatherBaseData;
import com.szjlxh.domain.model.index.WeatherHourData;
import com.szjlxh.domain.model.index.WeatherSevenDay;

import java.io.IOException;
import java.util.List;

import javax.inject.Inject;

import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import rx.Subscriber;

/**
 * Created by liutao on 16/2/29.
 */
public class IndexPresenterImpl implements IIndexPresenter {

    private IIndexFragment indexFragment;
    private BaseWeatherInfoUserCase userCase;

    //    @Inject
//    public IndexPresenterImpl() {
//
//    }
    @Inject
    public IndexPresenterImpl(BaseWeatherInfoUserCase userCase) {
        this.userCase = userCase;
    }

    @Override
    public void refreshSevenDayWeatherData() {
        userCase.execute(new Subscriber<List<WeatherSevenDay>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                indexFragment.onSenvenDayWeatherDataLoadedFailed(e.getMessage());
            }

            @Override
            public void onNext(List<WeatherSevenDay> o) {
                indexFragment.onSevenDayWeatherDataLoaded(o);
            }
        }, BaseWeatherInfoUserCase.SEVEN_DAY_CODE);
//        //TODO 处理请求协议
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url(ConstantUrl.SEVEN_DAY_WEATHER_URL).build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
////TODO请求出错的情况
//                injectSimulateSevenDayWeatherData();
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String out = response.body().string();
//                    System.out.println(out);
//                    WeatherSevenDayBean item = new Gson().fromJson(out, WeatherSevenDayBean.class);
//                    indexFragment.onSevenDayWeatherDataLoaded(item);
//                } else {
////                    notifyFailed("请求出错啦");
//                    injectSimulateSevenDayWeatherData();
//                }
//            }
//        });
    }

    @Override
    public void refreshSunData() {
        userCase.execute(new Subscriber<SunInfo>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
//                Toast.makeText(indexFragment.)
                injectSunData();
                Log.i("test", e.getMessage());
            }

            @Override
            public void onNext(SunInfo sunInfo) {
                indexFragment.onSunDataLoaded(sunInfo);
            }
        });
//        NetWorkSource netWorkSource = new NetWorkSource.Builder<SunDataBean>(ConstantUrl.SUN_DOWN_UP_URL).buildCallBack(new NetWorkSource.INetWorkHandler<SunDataBean>() {
//
//            @Override
//            public void onSucess(SunDataBean data) {
//                indexFragment.onSunDataLoaded(data);
//            }
//
//            @Override
//            public void onFailed(String data) {
//                injectSunData();
//            }
//        }).build();
//        netWorkSource.sendRequest(SunDataBean.class);

//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url(ConstantUrl.SUN_DOWN_UP_URL).build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//                injectSunData();
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String out = response.body().string();
//                    System.out.println(out);
//                    SunDataBean item = new Gson().fromJson(out, SunDataBean.class);
//                    indexFragment.onSunDataLoaded(item);
//                } else {
//                    injectSunData();
//                }
//            }
//        });
    }

    public void test() {
        OkHttpClient client = new OkHttpClient();
        Request request = new Request.Builder().url("http://10.124.102.170:8080/statellite/GetWeatherCode").build();
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {
                injectSunData();
            }

            @Override
            public void onResponse(Response response) throws IOException {
                if (response.isSuccessful()) {
                    String out = response.body().string();
                    System.out.println(out);
                    test item = new Gson().fromJson(out, test.class);
                    //

                    StringBuilder sb = new StringBuilder();
                    for (int i = 0; i < item.getResult().size(); i++) {
                        sb.append("\"" + item.getResult().get(i).getWEATHERCODE() + "\",");
                    }
                    System.out.println(sb.toString());

                    StringBuilder sb1 = new StringBuilder();
                    for (int i = 0; i < item.getResult().size(); i++) {
                        sb1.append("\"" + item.getResult().get(i).getWEATHERNAME() + "\",");
                    }
                    System.out.println(sb1.toString());
                } else {
                    injectSunData();
                }
            }
        });
    }

    @Override
    public void refreshBaseWeaterData() {
        userCase.execute(new Subscriber<WeatherBaseData>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                indexFragment.onWeatherBaseLOadedFailed(e.getMessage());
            }

            @Override
            public void onNext(WeatherBaseData o) {
                indexFragment.onWeatherBaseLoaded(o);
            }
        }, BaseWeatherInfoUserCase.BASE_WEATHER_CODE);
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url(ConstantUrl.INSTANT_WEATHER_URL).build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
//                indexFragment.onWeatherBaseLOadedFailed(e.getMessage());
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String out = response.body().string();
//                    System.out.println(out);
//                    WeatherBaseBean item = new Gson().fromJson(out, WeatherBaseBean.class);
//                    indexFragment.onWeatherBaseLoaded(item);
//                } else {
//                    indexFragment.onWeatherBaseLOadedFailed(response.message());
//                }
//            }
//        });
    }

    @Override
    public void refreshLast24HoursData() {
        userCase.execute(new Subscriber<List<WeatherHourData>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                indexFragment.onLast24HoursWeatherDataLoadedFailed(e.getMessage());
            }

            @Override
            public void onNext(List<WeatherHourData> o) {
                indexFragment.onLast24HoursWeatherDataLoaded(o);
            }
        }, BaseWeatherInfoUserCase.LAST_24_HOUR_CODE);
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url(ConstantUrl.LAST_24_HOURS_URL).build();
//        client.newCall(request).enqueue(new Callback() {
//                                            @Override
//                                            public void onFailure(Request request, IOException e) {
//                                                inject24HoursWeather(true);
//                                            }
//
//                                            @Override
//                                            public void onResponse(Response response) throws IOException {
//                                                if (response.isSuccessful()) {
//                                                    String out = response.body().string();
//                                                    System.out.println(out);
//                                                    HoursWeatherBean item = new Gson().fromJson(out, HoursWeatherBean.class);
//                                                    if (item == null || item.getResult() == null) {
//                                                        inject24HoursWeather(true);
//                                                        return;
//                                                    }
//                                                    indexFragment.onLast24HoursWeatherDataLoaded(item);
//                                                } else {
////                    notifyFailed("请求出错啦");
//                                                    inject24HoursWeather(true);
//                                                }
//                                            }
//                                        }
//
//        );
    }

    @Override
    public void refreshFuture24HoursData() {
        userCase.execute(new Subscriber<List<WeatherHourData>>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                indexFragment.onFuture24HoursWeatherDataLoadedFailed(e.getMessage());
            }

            @Override
            public void onNext(List<WeatherHourData> o) {
                indexFragment.onFuture24HoursWeatherDataLoaded(o);
            }
        }, BaseWeatherInfoUserCase.FUTURE_24_HOUR_CODE);
//        OkHttpClient client = new OkHttpClient();
//        Request request = new Request.Builder().url(ConstantUrl.FUTURE_24_HOURS_URL).build();
//        client.newCall(request).enqueue(new Callback() {
//            @Override
//            public void onFailure(Request request, IOException e) {
////TODO请求出错的情况
//                inject24HoursWeather(false);
//            }
//
//            @Override
//            public void onResponse(Response response) throws IOException {
//                if (response.isSuccessful()) {
//                    String out = response.body().string();
//                    System.out.println(out);
//                    HourForcastBean item = new Gson().fromJson(out, HourForcastBean.class);
//                    if (item == null || item.getWEATHERDATA() == null) {
//                        inject24HoursWeather(false);
//                        return;
//                    }
//                    indexFragment.onFuture24HoursWeatherDataLoaded(item);
//                } else {
////                    notifyFailed("请求出错啦");
//                    inject24HoursWeather(false);
//                }
//            }
//        });
    }

    @Override
    public void loadData() {
        indexFragment.onRefreshData();
    }

    @Override
    public void onDestory() {
        indexFragment.onDestory();
    }

    @Override
    public void refreshStation() {
        //获取地理位置管理器
        LocationManager locationManager = (LocationManager) indexFragment.getContextInstance().getSystemService(Context.LOCATION_SERVICE);
        //获取所有可用的位置提供器
        List<String> providers = locationManager.getProviders(true);
        String locationProvider;
        if (providers.contains(LocationManager.GPS_PROVIDER)) {
            //如果是GPS
            locationProvider = LocationManager.GPS_PROVIDER;
        } else if (providers.contains(LocationManager.NETWORK_PROVIDER)) {
            //如果是Network
            locationProvider = LocationManager.NETWORK_PROVIDER;
        } else {
            indexFragment.onStationLoadedFailed();
//            Toast.makeText(this, "没有可用的位置提供器", Toast.LENGTH_SHORT).show();
            return;
        }
        //获取Location

        //检查权限

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.M) {

            int result = ContextCompat.checkSelfPermission(indexFragment.getContextInstance(), "android.permission.ACCESS_FINE_LOCATION");
            if (result == PackageManager.PERMISSION_DENIED) {
                AndroidApplication.getInstance().showToastMessage("没有定位权限，请先开启");
                return;
            }
        }
        Location location = locationManager.getLastKnownLocation(locationProvider);
        if (location != null) {
            //不为空,显示地理位置经纬度
            requestStationNameByLocation(location);
        }
        //监视地理位置变化
        locationManager.requestLocationUpdates(locationProvider, 3000, 1, new LocationListener() {
            @Override
            public void onLocationChanged(Location location) {
                requestStationNameByLocation(location);
            }

            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {

            }

            @Override
            public void onProviderEnabled(String provider) {

            }

            @Override
            public void onProviderDisabled(String provider) {

            }
        });
    }

    private void requestStationNameByLocation(Location location) {
        userCase.execute(new Subscriber<Station>() {
            @Override
            public void onCompleted() {

            }

            @Override
            public void onError(Throwable e) {
                indexFragment.onStationLoaded("定位失败");
            }

            @Override
            public void onNext(Station o) {
                indexFragment.onStationLoaded(o.getName());

            }
        }, location.getLongitude() + "", location.getLatitude() + "");
    }

    //以下是模拟数据
//
//    private void injectSimulateSevenDayWeatherData() {
//        WeatherSevenDayBean weatherDayInfoBean = new WeatherSevenDayBean();
//        List<WeatherSevenDayBean.DataEntity> dataEntities = new ArrayList<>();
//
//        WeatherSevenDayBean.DataEntity weatherDayInfo = new WeatherSevenDayBean.DataEntity();
////        weatherDayInfo.setWeekday("星期X");
//        weatherDayInfo.setMonth(3);
//        weatherDayInfo.setDay(9);
//        weatherDayInfo.setWeather("阴天");
//        weatherDayInfo.setTempMax(12);
//        weatherDayInfo.setTempMin(2);
//        weatherDayInfo.setWindB("东北风");
//        weatherDayInfo.setWind("4-5级");
//        for (int i = 1; i <= 7; i++) {
//            dataEntities.add(weatherDayInfo);
//        }
//        weatherDayInfoBean.setData(dataEntities);
////        weather_report.setWeatherDayInfos(weatherDayInfoBean);
//        indexFragment.onSenvenDayWeatherDataLoadedFailed(weatherDayInfoBean);
//    }


//    private void inject24HoursWeather(boolean isLast) {
//        HoursWeatherBean.ResultEntity resultEntity = new HoursWeatherBean.ResultEntity();
//        resultEntity.setHOUR("xx");
//        resultEntity.setWEATHER("良好");
//        resultEntity.setTEMP("1");
//        resultEntity.setWIND_DICRECT("111");
//        resultEntity.setWIND_SCALE("3");
//        resultEntity.setHOUR_RAIN("300");
//        HoursWeatherBean f = new HoursWeatherBean();
//        List<HoursWeatherBean.ResultEntity> data = new ArrayList<>();
//        for (int i = 0; i < 24; i++) {
//            data.add(resultEntity);
//        }
//        f.setResult(data);
////        if (!isLast)
//////            indexFragment.onFuture24HoursWeatherDataLoadedFailed(f);
////        else
//            indexFragment.onLast24HoursWeatherDataLoadedFailed(f);
//    }

    private void injectSunData() {
        SunInfo sunDataBean = new SunInfo();
        sunDataBean.setDownriseTime("06:15");
        sunDataBean.setDowndownTime("17:12");
        indexFragment.onSunDataFailed(sunDataBean);
    }


    public void setIndexFragment(IIndexFragment indexFragment) {
        this.indexFragment = indexFragment;
    }
}
